package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Sets;
import com.zhijian.medical.dao.local.NgsWkzbq1Mapper;
import com.zhijian.medical.entity.dto.SangerHskzyqInsideDto;
import com.zhijian.medical.entity.dto.SangerHskzyqOutsideDto;
import com.zhijian.medical.entity.dto.SangerSjpzqPcrDto;
import com.zhijian.medical.entity.po.ExperimentProcessSampleLog;
import com.zhijian.medical.entity.po.Ngs;
import com.zhijian.medical.entity.po.NgsWkzbq1;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.request.NgsWkzbq1SaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.NgsWkzbq1SearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.NgsHszbqVo;
import com.zhijian.medical.entity.vo.response.NgsWkzbq1Vo;
import com.zhijian.medical.enums.AllExperimentationStepStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.NgsStatusEnum;
import com.zhijian.medical.enums.StatusEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.*;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 二代测序-文库制备区 （片段化）业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-08-23 15:04:35
 */
@Slf4j
@Service
public class NgsWkzbq1ServiceImpl implements NgsWkzbq1Service {

    @Autowired
    private NgsWkzbq1Mapper mapper;

    @Autowired
    private NgsHszbqService ngsHszbqService;

    @Autowired
    private NgsService ngsService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessSampleLogService experimentProcessSampleLogService;

    @Override
    public NgsWkzbq1 selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public NgsWkzbq1 selectByNgsId(Long ngsId) {
        return mapper.selectByNgsId(ngsId);
    }

    @Override
    public NgsWkzbq1Vo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public NgsWkzbq1Vo selectVoByNgsId(Long ngsId) {
        NgsWkzbq1Vo ngsWkzbq1Vo = mapper.selectVoByNgsId(ngsId);
        if (Objects.isNull(ngsWkzbq1Vo)) {
            return null;
        }
        Ngs ngs = ngsService.selectById(ngsId);
        if (Objects.isNull(ngs)) {
            return null;
        }
        ngsWkzbq1Vo.setResult(ngs.getStatus() > NgsStatusEnum.WKZBQ1.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        ngsWkzbq1Vo.setResultStr(ngs.getStatus() > NgsStatusEnum.WKZBQ1.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        String data = ngsWkzbq1Vo.getData();
        if (StringUtils.isNotBlank(data)) {
            ngsWkzbq1Vo.setDataList(JsonUtil.toArray(data, SangerHskzyqOutsideDto.class));
        }
        return ngsWkzbq1Vo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByNgsId(Long ngsId) {
        mapper.deleteByNgsId(ngsId);
    }

    @Override
    public Long insert(NgsWkzbq1 ngsWkzbq1) {
        Date now = new Date();
        ngsWkzbq1.setCreateTime(now);
        ngsWkzbq1.setUpdateTime(now);
        ngsWkzbq1.setAzfzsopoxxjxbccssd(StatusEnum.UN_NORMAL.getCode().byteValue());
        ngsWkzbq1.setPcr(StatusEnum.NORMAL.getCode().byteValue());
        return mapper.insert(ngsWkzbq1) > 0 ? ngsWkzbq1.getId() : 0L;
    }

    @Override
    public boolean update(NgsWkzbq1 ngsWkzbq1) {
        Date now = new Date();
        ngsWkzbq1.setUpdateTime(now);
        return mapper.updateByPrimaryKey(ngsWkzbq1) != 0;
    }

    @Override
    public Integer count(NgsWkzbq1SearchVo ngsWkzbq1SearchVo) {
        return mapper.count(ngsWkzbq1SearchVo);
    }

    @Override
    public List<NgsWkzbq1Vo> selectList(NgsWkzbq1SearchVo ngsWkzbq1SearchVo) {
        return mapper.selectList(ngsWkzbq1SearchVo);
    }

    @Override
    public Page<NgsWkzbq1Vo> selectPage(NgsWkzbq1SearchVo ngsWkzbq1SearchVo) {
        //先直接查总数
        int count = count(ngsWkzbq1SearchVo);
        //分页
        Page<NgsWkzbq1Vo> page = new Page<>(true, count, ngsWkzbq1SearchVo.getPageNum(), ngsWkzbq1SearchVo.getPageSize());
        ngsWkzbq1SearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<NgsWkzbq1Vo> responseVos = this.selectList(ngsWkzbq1SearchVo);
        page.setData(responseVos);
        return page;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(NgsWkzbq1SaveOrUpdateVo ngsWkzbq1SaveOrUpdateVo) {
        Long ngsId = ngsWkzbq1SaveOrUpdateVo.getNgsId();
        Ngs ngs = ngsService.selectById(ngsId);
        AssertUtil.notNull(ngs, "此实验不存在或者已被删除");
        if (ngs.getStatus() < NgsStatusEnum.WKZBQ2.getCode().byteValue()) {
            //修改实验的状态
            ngsService.updateByPrimaryKeySelective(Ngs.builder()
                    .id(ngsId)
                    .status(NgsStatusEnum.WKZBQ2.getCode().byteValue())
                    .build());
        }
        List<SangerHskzyqOutsideDto> dataList = ngsWkzbq1SaveOrUpdateVo.getDataList();
        if (CollectionUtil.isNotEmpty(dataList)) {
            //如果传了表格数据，前端只会传编号，要把编号对应的分子病理号查出来，也就是去试剂配置区里查
            NgsHszbqVo ngsHszbqVo = ngsHszbqService.selectVoByNgsId(ngsId);
            AssertUtil.notNull(ngsHszbqVo, "还未完成核酸制备区 ");
            List<SangerSjpzqPcrDto> pdhfyybDataList = ngsHszbqVo.getPdhfyybDataList();
            AssertUtil.check(CollectionUtil.isEmpty(pdhfyybDataList), "还未完成核酸制备区 -片段化反应样本编号");

            Set<Integer> set = Sets.newHashSet();
            //试剂配置区的PCR的数据
            dataList.forEach(sangerHskzyqOutsideDto -> {
                List<List<SangerHskzyqInsideDto>> sangerHskzyqOutsideDtoData = sangerHskzyqOutsideDto.getData();
                if (CollectionUtil.isNotEmpty(sangerHskzyqOutsideDtoData)) {
                    sangerHskzyqOutsideDtoData.forEach(sangerHskzyqInsideDtos -> {
                        if (CollectionUtil.isNotEmpty(sangerHskzyqInsideDtos)) {
                            sangerHskzyqInsideDtos.stream().filter(s -> Objects.nonNull(s.getBh())).forEach(sangerHskzyqInsideDto -> {
                                //编号
                                Integer bh = sangerHskzyqInsideDto.getBh();
                                AssertUtil.check(!set.add(bh), "反应孔数据不允许有重复编号");
                                //筛选出编号一样的数据
                                SangerSjpzqPcrDto sangerSjpzqPcrDto = pdhfyybDataList.stream().filter(s -> s.getNumber().equals(bh)).findFirst().orElse(null);
                                sangerHskzyqInsideDto.setFzblh(Objects.nonNull(sangerSjpzqPcrDto) ? String.format("%s-%s", sangerSjpzqPcrDto.getFzblh(), sangerSjpzqPcrDto.getProject()) : null);
                            });
                        }
                    });
                }
            });
            ngsWkzbq1SaveOrUpdateVo.setData(JsonUtil.toString(dataList));
        }
        NgsWkzbq1 dbParam = new NgsWkzbq1();
        BeanUtils.copyProperties(ngsWkzbq1SaveOrUpdateVo, dbParam);
        NgsWkzbq1 oldNgsWkzbq1 = this.selectByNgsId(ngsId);
        if (Objects.isNull(oldNgsWkzbq1)) {
            this.insert(dbParam);
        } else {
            dbParam.setId(oldNgsWkzbq1.getId());
            this.update(dbParam);
        }
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.NGS.getCode().byteValue())
                .experimentProcessId(ngsId)
                .build());
        //保存样本日志
        experimentProcessSampleLogService.saveBatch(experimentProcessSampleVos.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(ngsId)
                .mainType(ExperimentTypeEnum.NGS.getCode().byteValue())
                .op(String.format("%s%s-%s", ngs.getName(), ngs.getProcessNumber(), NgsStatusEnum.WKZBQ1.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

}